<template>
  <div class="details">
    <div class="header"></div>

    <van-loading size="39px" vertical type="spinner" v-if="chunkIndex == 0"
      >加载中...</van-loading
    >
    <div class="content" v-if="tokenImages.length">
      <van-cell is-link @click="showPopup"
        ><div
          class="img"
          v-for="(chunk, chindex) in tokenImages"
          :key="chindex"
        >
          <van-image
            v-for="(item, index) in chunk"
            :key="index"
            width="375"
            :height="`${
              (chunkedImages[chindex][index]?.y /
                chunkedImages[chindex][index]?.x) *
              375
            }`"
            lazy-load
            :src="`${item.url}?token=${item.token}`"
          >
            <template v-slot:loading>
              <van-loading type="spinner" size="20" />
            </template>
          </van-image></div
      ></van-cell>
      <van-popup v-model="show" position="top" :style="{ height: '5%' }">
        <div class="top">
          <span class="back iconfont icon-zuojiantou" @click="prev"></span>
          <span class="title">{{ detail.title }}</span>
          <span class="sort">第{{ last_ep.short_title }}话</span>
        </div>
      </van-popup>

      <van-popup
        v-model="show"
        :overlay="false"
        position="bottom"
        :style="{ height: '10%' }"
      >
        <div class="choose">
          <span class="prev" @click="toPrevep">上一话</span>
          <span class="next" @click="toNextep">下一话</span>
        </div>
      </van-popup>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      images: [],
      chunkedImages: [],
      tokenImages: [],
      urls: "",
      chunkIndex: 0,
      epIndex: null, //当前章节序号
      nextepIndex: null, //下一章节
      prevepIndex: null, //上一章节
      commicId: null,
      epid: null,
      ep_list: [],
      show: false,
      detail: [],
      last_ep: [], //当前章节
    };
  },
  created() {
    this.commicId = this.$route.query.commicId;
    this.epid = this.$route.query.epid;
    localStorage.setItem(
      "history",
      JSON.stringify({ [this.commicId]: this.epid })
    );

    this.axios
      .get(`GetImageIndex?epId=${this.$route.query.epid}`)
      .then((res) => {
        this.images = res.data.data.images;
        // console.log(this.images);
        this.chunkedImages = new Array(
          Math.ceil(res.data.data.images.length / 10)
        )
          .fill(null)
          .map((o, i) => res.data.data.images.slice(i * 10, (i + 1) * 10));
        // console.log(this.chunkedImages);
        this.urls = JSON.stringify(
          this.chunkedImages[this.chunkIndex].map(
            (o) => o.path + "@760w_380h.jpg"
          )
        );
        // console.log(this.urls);

        this.axios.get(`ImageToken?urls=${this.urls}`).then((res) => {
          // let tokenImages = this.tokenImages;
          // this.tokenImages = []
          this.tokenImages[this.chunkIndex] = res.data.data;
          // this.tokenImages = tokenImages;
          this.chunkIndex = this.chunkIndex + 1;
          // console.log(this.tokenImages);
        });
      });

    this.axios
      .get(`/ComicDetail?comicId=${this.$route.query.commicId}`)
      .then((res) => {
        // console.log(res.data.data.ep_list.reverse());
        console.log(res.data.data);
        this.detail = res.data.data;
        this.ep_list = res.data.data.ep_list.reverse();

        // console.log(this.ep_list);
        // localStorage.setItem("ep_list", JSON.stringify(this.ep_list));
      });
    // console.log(this.$route.query.id);
  },
  mounted() {
    // console.log(this.tokenImages);
    this.getScroll();
    window.addEventListener("scroll", this.getScroll);
  },
  
  methods: {
    prev() {
      this.$router.back();
      this.ep_list = [];
    },

    showPopup() {
      this.show = true;
    },
    toNextep() {
      this.epIndex = this.ep_list.findIndex((o) => o.id == this.epid);
      this.nextepIndex = this.epIndex + 1;
      // this.chunkIndex = 0;
      this.show = false;
      if (this.nextepIndex <= this.ep_list.length) {
        this.epid = this.ep_list[this.nextepIndex].id;
        this.$router.replace({
          path: "/details",
          query: {
            commicId: this.$route.query.commicId,
            epid: this.ep_list[this.nextepIndex].id,
          },
        });
      } else {
        this.$toast("已经是最后一章啦！");
      }
    },
    toPrevep() {
      this.epIndex = this.ep_list.findIndex((o) => o.id == this.epid);
      this.prevepIndex = this.epIndex - 1;
      this.show = false;
      if (this.prevepIndex >= 0) {
        this.epid = this.ep_list[this.prevepIndex].id;
        //  this.chunkIndex = 0;
        this.$router.replace({
          path: "/details",
          query: {
            commicId: this.$route.query.commicId,
            epid: this.ep_list[this.prevepIndex].id,
          },
        });
      } else {
        this.$toast("没有上一章啦！");
      }
    },
    getScroll() {
      this.epid = this.$route.query.epid;
      // console.log(this.ep_list);
      let scrolltop = Math.ceil(document.documentElement.scrollTop); //获取当前滚动高度
      let clienHeight = document.documentElement.clientHeight; //获取屏幕高度
      let scrollHeight = document.documentElement.scrollHeight; //获取屏幕高度
      //   console.log("当前高度==>", scrolltop);
      //   console.log("屏幕高度==>", clienHeight);
      //   console.log("内容高度==>", scrollHeight);
      if (scrolltop + clienHeight >= scrollHeight) {
        // console.log("触底");
        // console.log(this.chunkIndex);
        // console.log(this.chunkedImages);
        if (this.chunkIndex <= this.chunkedImages.length - 1) {
          // console.log("加载分页");
          this.urls = JSON.stringify(
            this.chunkedImages[this.chunkIndex].map(
              (o) => o.path + "@760w_380h.jpg"
            )
          );
          // console.log(this.urls);
          this.axios.get(`ImageToken?urls=${this.urls}`).then((res) => {
            // this.tokenImages=[];
            this.tokenImages[this.chunkIndex] = res.data.data;
            // this.tokenImages = tokenImages;
            this.chunkIndex = this.chunkIndex + 1;
            // console.log(tokenImages);
          });
        } else {
          // console.log("所有分页加载完成");
          //判断本地存有无当前漫画所有章节列表

          if (this.ep_list) {
            //计算下一章
            // console.log(this.ep_list);
            this.epIndex = this.ep_list.findIndex((o) => o.id == this.epid);
            if (this.epIndex >= this.ep_list.length - 1) {
              //最后一章
            } else {
              //跳到后一章
              // console.log(this.ep_list);
              // console.log("下一章");
              this.nextepIndex = this.epIndex + 1;
              // console.log(this.ep_list);
              // console.log("当前id", this.epid);
              // console.log("下一章id", this.ep_list[this.nextepIndex].id);
              // this.tokenImages = [];
              this.chunkIndex = 0;
              this.$router.replace({
                path: "/details",
                query: {
                  commicId: this.$route.query.commicId,
                  epid: this.ep_list[this.nextepIndex].id,
                },
              });
            }
          } else {
            //获取所有章节列表
            this.axios
              .get(`/ComicDetail?comicId=${this.$route.query.commicId}`)
              .then((res) => {
                //计算下一章id
                // console.log(res.data.data.ep_list.reverse());
                this.ep_list = res.data.data.ep_list.reverse();
                // console.log(this.ep_list);
                // localStorage.setItem("ep_list", JSON.stringify(this.ep_list));
              });
            // console.log(this.$route.query.id);
          }
        }
      }
    },
  },
  watch: {
    epid: function (newValue, oldValue) {
      console.log(newValue, oldValue);
      this.chunkIndex = 0;
      this.images = [];
      this.chunkedImages = [];
      this.tokenImages = [];
      this.commicId = this.$route.query.commicId;
      this.epid = this.$route.query.epid;
      console.log(this.epid);
      console.log(this.chunkedImages);
      localStorage.setItem(
        "history",
        JSON.stringify({ [this.$route.query.commicId]: this.epid })
      );

      this.axios
        .get(`GetImageIndex?epId=${this.$route.query.epid}`)
        .then((res) => {
          this.images = res.data.data.images;
          console.log(this.images);
          this.chunkedImages = new Array(
            Math.ceil(res.data.data.images.length / 10)
          )
            .fill(null)
            .map((o, i) => res.data.data.images.slice(i * 10, (i + 1) * 10));
          console.log(this.chunkedImages);
          this.urls = JSON.stringify(
            this.chunkedImages[this.chunkIndex].map(
              (o) => o.path + "@760w_380h.jpg"
            )
          );
          // console.log(this.urls);

          this.axios.get(`ImageToken?urls=${this.urls}`).then((res) => {
            // let tokenImages = this.tokenImages;
            this.tokenImages = [];
            this.chunkIndex = 0;
            this.tokenImages[this.chunkIndex] = res.data.data;
            // this.tokenImages = tokenImages;
            this.chunkIndex = this.chunkIndex + 1;
            // console.log(this.tokenImages);
          });
          this.axios
            .get(`/ComicDetail?comicId=${this.$route.query.commicId}`)
            .then((res) => {
              this.last_ep = res.data.data.ep_list.find(
                (o) => o.id == this.epid
              );
            });
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.details {
  padding-bottom: 70px;
  .header {
    height: 50px;
    padding: 0px 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    top: 0;
    left: 0px;
    z-index: 10;
  }
  .content {
    .img {
      width: 100%;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
  .choose {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 12px;
  }
  .next,
  .prev {
    display: inline-block;
    width: 135px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    font-size: 14px;
    color: #fff;
    background-color: #fe5153;
    border-radius: 25px;
    margin-top: 15px;
    // position: absolute;
    // margin-left: 200px;
  }
  .top {
    display: flex;
    align-items: center;
    padding: 5px 20px 5px 12px;
    .title {
      font-size: 16px;
      color: #333;
      font-weight: bold;
      margin-right: 20px;
    }
    .sort {
      font-size: 14px;
      color: #fe5153;
    }
  }
  .back {
    font-size: 22px;
    color: #333;
    margin-right: 10px;
  }

  .van-loading--vertical {
    margin-top: 300px;
  }
  .van-cell__value {
    width: 375px;
  }
  .van-cell__right-icon {
    font-size: 0;
    margin: 0;
  }
  .van-cell {
    padding: 0;
  }
}
</style>